import { useState,useEffect } from "react";
import {FetchService} from "@/utils/request";
import Ctable from "@/components/commonTable";
import {resType} from "@/commonType";
import { Pagination,Button,message,Image} from "antd";
import  type { TableProps } from 'antd';
import DynamicFormModal from '@/components/commonDialog';

type TablePagination<T extends object> = NonNullable<Exclude<TableProps<T>['pagination'], boolean>>;
type TablePaginationPosition<T extends object> = NonNullable<
  TablePagination<T>['position']
>[number];

const fetchService = new FetchService();


type DataType = {
    id: number;
    name:string;
    category:string;//0：绳子  1：珠子  2：配饰  3：其他
    image_url:string;
    stock: number;//库存数量,用户下单后更新库存
    buying_price: number;//采购价格
    selling_price: number;//销售价格
    description: string;
    diameter: number;//直径
    length: number;//长度
    material:string;//材质
    color:string;//颜色
    manufacturer:string; //制造商
    origin:string; //产地
    weight:number; //重量
    status:string; //状态 0：上架  1：下架
    create_at:Date;
    update_at: Date;
}
  

const addMaterialOpts = [
  {
      name:"物料名称",
      key:"name",
      component:"input",
      span:12,
      required:true
  },
  {
      name:"类型",
      key:"category",
      component:"select",
      items:[
        {label:"绳子",value:"0"},
        {label:"珠子",value:"1"},
        {label:"配饰",value:"2"},
        {label:"其他",value:"3"},
      ],
      span:12,
      required:true
  },
  {
      name:"库存数量",
      key:"stock",
      component:"input",
      span:12,
      required:true
  },
  {
      name:"采购价格（元）",
      key:"buying_price",
      component:"input",
      span:12,
      required:true
  },
  {
      name:"销售价格（元）",
      key:"selling_price",
      component:"input",
      span:12,
      required:true
  },
  {
      name:"直径（mm）",
      key:"diameter",
      component:"input",
      span:12,
      required:false
  },
  {
      name:"长度（mm）",
      key:"length",
      component:"input",
      span:12,
      required:false
  },
  {
      name:"材质",
      key:"material",
      component:"input",
      span:12,
      required:false
  },
  {
      name:"颜色",
      key:"color",
      component:"input",
      span:12,
      required:false
  },
  {
      name:"制造商",
      key:"manufacturer",
      component:"input",
      span:12,
      required:false
  },
  {
      name:"产地",
      key:"origin",
      component:"input",
      span:12,
      required:false
  },
  {
      name:"质量（g）",
      key:"weight",
      component:"input",
      span:12,
      required:false
  },
  {
      name:"状态",
      key:"status",
      component:"select",
      items:[
        {label:"上架",value:"1"},
        {label:"下架",value:"0"}
      ],
      span:12,
      required:false
  }, 
  {
    name:"预览图",
    key:"image_url",
    component:"upload",
    span:24,
    required:false
  },
  {
    name:"描述",
    key:"description",
    component:"textarea",
    span:24,
    required:false
  }
]





const MaterialList:React.FC = () => {
    const [tableData,setTableData] = useState<any[]>([]);
    const [page,setPage] = useState({pageNum:1,pageSize:10});
    const [total,setTotal] = useState<number>(0);
    const [bottom, setBottom] = useState<TablePaginationPosition<DataType>>('bottomRight');
    const [addDialogVisible, setAddDialogVisible] = useState(false);
    const [dialogTitle, setDialogTitle] = useState("添加物料信息")
    const [currentRowId, setCurrentRowId] = useState<number | null>(null);
    const [formData, setFormData] = useState<any>({
        name:"",
        category:0,
        stock:0,
        buying_price:0,
        selling_price:0,
        description:"",
        diameter:0,
        length:0,
        material:"",
        color:"",
        manufacturer:"",
        origin:"",
        weight:0,
        image_url:"",
        id:null,
        status:"0"
    });
    const columns = [
      {
        title: '物料名称',
        dataIndex: 'name',
        key: 'name',
        width:120,
        searchable: true,
      },
      {
        title: '类型',
        dataIndex: 'category',
        width:120,
        key: 'category',
        searchable: true,
        render: (text:string) => {
          return text == '0' ? "绳子" : text == '1' ? "珠子" : text == '2' ? "配饰" : "其他"
        }
      },
      {
        title: '预览图',
        dataIndex: 'image_url',
        key: 'image_url',
        width:120,
        render: (text:string) => {
          if(!text) return <div>暂无图片</div>
          return <Image
                    width={100}
                    src={"http://localhost:3000/" + text}
                  />
        },
      },
      {
        title: '库存',
        dataIndex: 'stock',
        key: 'stock',
        width:100,
        searchable: true,
      },
      {
        title: '采购价格（元）',
        width:120,
        dataIndex: 'buying_price',
        key: 'buying_price',
        searchable: true,
      },
      {
        title: '销售价格（元）',
        width:120,
        dataIndex: 'selling_price',
        key: 'selling_price',
        searchable: true,
      },
      {
        title: '直径（mm）',
        width:100,
        dataIndex: 'diameter',
        key: 'diameter',
      },
      {
        title: '长度（mm）',
        width:100,
        dataIndex: 'length',
        key: 'length',
      },
      {
        title: '材质',
        width:100,
        dataIndex: 'material',
        key: 'material',
      },
      {
        title: '颜色',
        width:100,
        dataIndex: 'color',
        key: 'color',
      },
      {
        title: '制造商',
        width:120,
        dataIndex: 'manufacturer',
        key: 'manufacturer',
      },
      {
        title: '产地',
        width:130,
        dataIndex: 'origin',
        key: 'origin',
      },
      {
        title: '质量（g）',
        width:100,
        dataIndex: 'weight',
        key: 'weight',
      },
      {
        title: '入库时间',
        dataIndex: 'create_at',
        width:120,
        key: 'create_at',
        searchable: true,
      },
      {
        title: '修改时间',
        dataIndex: 'update_at',
        width:120,
        key: 'update_at',
      },
      {
        title: '状态',
        dataIndex: 'status',
        width:90,
        key: 'status',
        render: (text:string) => {
          console.log(text,'text');
          return text == '0' ? "下架" : text == '1'?'上架':'废弃';
        }
      },
      {
        title: '描述',
        dataIndex: 'description',
        width:150,
        key: 'description',
      },
      {
        title: '操作',
        dataIndex: 'op',
        key: 'op',
        width:180,
        render: (text:string,record:DataType) => {
          return <div>
              <Button type="primary" onClick={() => editMaterial(record)}>编辑</Button>
              <Button style={{marginLeft:10,marginRight:10}} color="danger" variant="solid" onClick={() => deleteProduct(record.id)}>删除</Button>
          </div>
      }
    }
    ];
    const getMaterialList = async () => {
      let res:resType = await fetchService.get("/product/findMaterial",page);
        if(res.code === 200) {
          let tdata:any = [];
          res.data.data.map((item:DataType) => {
            tdata.push({
                id: item.id,
                name:item.name,
                category:item.category,//0：绳子  1：珠子  2：配饰  3：其他
                image_url:item.image_url,
                stock: item.stock,//库存数量,用户下单后更新库存
                buying_price: item.buying_price,//采购价格
                selling_price: item.selling_price,//销售价格
                description: item.description,
                diameter: item.diameter,//直径
                length: item.length,//长度
                material:item.material,//材质
                color:item.color,//颜色
                manufacturer:item.manufacturer, //制造商
                origin:item.origin, //产地
                weight:item.weight, //重量
                create_at:item.create_at,
                update_at: item.update_at,
                status:item.status,//0：下架  1：上架 2：废弃
            })
          })
          setTotal(res.data.total)
          setTableData(tdata);
        }
    }
    useEffect(()=>{
      getMaterialList();
    },[])
    const search = (info:any)=>{
        console.log(info);
        getMaterialList();
    }
    
    const editMaterial = (row:any)=>{
      console.log(row,'row')
      setCurrentRowId(row.id)
      setFormData(row)
      setAddDialogVisible(true)
    
    }
    const deleteProduct = async (id:number)=>{
      console.log(id)
      let res:resType = await fetchService.post("/product/removeMaterial",[id]);
      if(res.code === 200) {
        message.success("删除成功")
        getMaterialList()
      }else{
        message.error(res.msg)
      }
    }
    const addMaterial = ()=>{
      setAddDialogVisible(true)
    }

    const handleSave = async (form:any)=>{
      console.log(form)
      if(currentRowId){
        form.id = currentRowId;
        let res:resType = await fetchService.post("/product/updateMaterial",form);
        if(res.code === 200) {
          message.success("更新成功")
          getMaterialList()
          setAddDialogVisible(false)
        }
      }else{
        let res:resType = await fetchService.post("/product/addMaterial",form);
        if(res.code === 200) {
          message.success("添加成功")
          getMaterialList();
        }else{
          message.error(res.msg)
          setAddDialogVisible(false)
        }
      }
      
      
      

     
    }

    const handleChange = (changeItem:any,items:any)=>{
      console.log(changeItem)
      console.log(items)
    }
    
    
    return (
        <div>
            <Ctable
                dataSource={tableData}
                columns={columns}
                role={["add","edit","delete"]}
                searchable={true}
                rowKey="id"
                search={()=>{}}
                add={()=>{addMaterial()}}
            />
            <DynamicFormModal
              visible={addDialogVisible}
              onCancel={() => setAddDialogVisible(false)}
              formConfig={addMaterialOpts}
              onSave={handleSave}
              onChange={handleChange}
              formData={formData}
              modalWidth={800}
              title={dialogTitle}
            />
        </div>
    )
}

export default MaterialList;